from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
import uvicorn
import os

app = FastAPI()

import subprocess
from fastapi.responses import Response
from pathlib import Path

@app.get("/audio/{audio_id}")
async def get_audio(audio_id: int):
    lis = music_list("music")
    audio_id = audio_id % len(lis)
    ret = lis[audio_id]

    if ret.endswith(".pcm"):
        return FileResponse(f"music/{ret}", media_type="application/octet-stream")
    elif ret.endswith(".mp3"):
        mp3_path = Path("music") / ret
        result = encode_mp3(mp3_path)
        # 返回二进制PCM数据
        return Response(
            content=result.stdout,
            media_type="application/octet-stream"
        )
    else:
        raise HTTPException(500, detail="不支持的音频格式")


def music_list(filePath):
    ret = []
    for i in os.listdir(filePath):
        tmp = ''.join(i)
        ret.append(tmp)  
    return ret       


def encode_mp3(mp3_path):
    command = [
        "ffmpeg",
        "-i", str(mp3_path),        # 输入文件路径
        "-f", "s16le",              # 输出格式为有符号16位小端字节序
        "-acodec", "pcm_s16le",     # PCM编码器
        "-ar", "8000",             # 采样率48kHz
        "-ac", "1",                 # 单声道
        "-y",                       # 覆盖输出文件（虽然用管道但保持命令兼容）
        "-"                         # 输出到标准输出
    ]
    result = subprocess.run(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=True
    )
    return result


if __name__ == "__main__":
    lis = music_list("music")
    print(lis)

    uvicorn.run(app, host="0.0.0.0", port=8000)